import Taro, { Component } from '@tarojs/taro'
import { Button, Image, Text, View } from '@tarojs/components'
import './index.scss'
import classNames from 'classnames'
import { headImg, initGoodsSku, selectGoodsSku } from '@/utils/utils'
import { GoodsNumber, MemberPrice } from '@/components/index'


//  处理商品信息
const filterGoodsInfo = i => {
  return {
    skuId: '',
    isSku: i.isSku,
    images: headImg(i.images),
    productId: i.id,
    costPrice: i.costPrice,
    salePrice: i.salePrice,
    memberPrice: i.memberPrice,
    originPrice: i.originPrice,
    stockNumber: i.stockNumber
  }
}

//  是否购买
const isBuy = i => {
  return i.isSku ? i.skuId : true
}

//  获取商品信息
const getInfo = goods => {
  return goods
}

interface IProps {
  info: any //  商品信息
  onClose: Function //  取消事件
  isOpened: any //  显示隐藏
}

export default class ActionSheetGoods extends Component<IProps, {}> {
  state: any
  props: any

  static options = {
    addGlobalClass: true
  }

  constructor() {
    super(...arguments)
    this.state = {
      checked: [],
      //  选中的属性
      goodsNum: 1,
      //  商品信息
      goodsInfo: {},
      //  规格渲染数据
      specList: [],
      //  规格源数据
      tagsList: [],
      //  商品 sku 属性
      attrList: [],
      //  商品 sku 信息
      skuInfo: {},
      //  sku商品列表
      skuList: []
    }
  }

  componentWillReceiveProps(nextProps) {
    const { info } = nextProps
    if (info.timestamp !== this.props.info.timestamp) {
      console.log('----------------------------------------- init-sku -----------------------------------------')
      const { tagSnap, skuDetail } = info
      const goodsInfo = filterGoodsInfo(info)
      this.setState({
        skuInfo: goodsInfo,
        goodsInfo: goodsInfo
      })
      if (info.isSku) {
        const data = initGoodsSku(tagSnap, skuDetail, info.skuId)
        this.setState({
          goodsNum: info.number || 1,
          tagsList: data.tags,
          specList: data.tags,
          attrList: data.attrs,
          skuInfo: data.skuInfo,
          skuList: data.skuList,
        })
      }
    }
  }

  /**
   * 选中商品 sku
   * @param k 商品规格 key
   * @param key 商品属性 key
   */
  selectGoods(key, k, spec, attr) {
    if (spec.options.indexOf(attr) === -1) {
      return false
    }
    const { specList, skuList } = this.state
    const checked:any = []
    specList[k]['value'] = specList[k]['value'] === key ? undefined : key
    specList.map(spec => {
      spec.options = []
      if (spec.value >= 0) {
        checked.push(spec.list[spec.value])
      }
    })

    const data = selectGoodsSku(checked, specList, skuList)
    this.setState({
      checked,
      specList: data.tagList,
      skuInfo: data.goodsInfo
    })
  }

  /**
   * 设置商品数量
   * @param value 数量
   */
  changeGoodsNum(value) {
    this.setState({
      goodsNum: value
    })
  }

  /**
   * 确定选择
   */
  onConfirm() {
    const { onConfirm, isOpened } = this.props
    const { skuInfo, goodsNum } = this.state
    onConfirm(skuInfo, goodsNum, isOpened)
  }

  render() {
    const { info={}, isOpened, onClose } = this.props
    const { goodsNum, specList, skuInfo, goodsInfo } = this.state
    const disabled = !isBuy({ ...goodsInfo, ...skuInfo })
    const goods = getInfo({ ...goodsInfo, ...skuInfo })
    // @ts-ignore
    return (<View className='action-sheet-goods' catchtouchmove>
      <View className={classNames('fy-transition fade fy-mask', isOpened && 'show')} onClick={() => onClose()}/>
      <View className={classNames('good-box fy-transition slide-bottom fy-popup fy-popup--bottom fy-popup--round', isOpened && 'show')}>
        <View className='goods-info'>
          <Image src={goods.images} className='goods-img'/>
          <View className='other-info'>
            <View className='goods-price d-f a-i-f-e'>
              <View className='bnn-number sale-price m-r-20'>
                <Text className='unit'>￥</Text>{goods.salePrice}
              </View>
              {goods.memberPrice && <MemberPrice price={goods.memberPrice}/>}
            </View>
            <Text className='residue-num'>仅剩余{goods.stockNumber}件</Text>
            {info.isSku && !disabled && <View className='attr-box t-o-e-2'>
              已选：<Text className='select-text'>{goods.specList && goods.specList.join(',')}</Text>
            </View>}
          </View>
        </View>
        {info.isSku && <View className='spec-list'>
          {specList.map((spec, k) => {
            return (<View key={k} className='attr-box'>
              <View className='title'>{spec.name}</View>
              <View className='attr-list'>
                {spec.list.map((attr, key) => {
                  return (<View
                    key={key}
                    className={classNames('attr-item f-g-5', spec.value === key && 'active', spec.options.indexOf(attr) == -1 && 'disabled')}
                    onClick={this.selectGoods.bind(this, key, k, spec, attr)}>{attr}</View>)
                })}
              </View>
            </View>)
          })}
        </View>}
        <View className='num-box'>
          <View className='title'>数量</View>
          <GoodsNumber min={1} max={99} value={goodsNum} onChange={this.changeGoodsNum.bind(this)}/>
        </View>
        <Button disabled={disabled} className='submit-btn' hoverClass='hover-class--btn' onClick={this.onConfirm.bind(this)}>确定</Button>
      </View>
    </View>)
  }
}
